const pathToRegExp = require('path-to-regexp');
function Layer(path, handler) {
    this.path = path;
    this.handler = handler;
    this.regExp = pathToRegExp(this.path, (this.keys = []));
}
Layer.prototype.match = function (pathname) {
    if (this.path === pathname) { // 路径一样匹配成功
        return true
    }

    let matches = pathname.match(this.regExp);

    if (matches) {
        this.params = this.keys.reduce((memo, current, index) => (memo[current.name] = matches[index + 1], memo), {});

        console.log(this.params)
        return true;
    }


    if (!this.route) { // 如果没有route属性 说明是一个中间件
        if (this.path === '/') { // 路径为/表示匹配成功
            return true;
        }
        return pathname.startsWith(this.path + '/'); // 以中间件开头的也可以匹配到
    }

    return false;
}
Layer.prototype.handle_request = function (req, res, next) {
    return this.handler(req, res, next);
}
Layer.prototype.handle_error = function (err, req, res, next) {
    return this.handler(err, req, res, next);
}
module.exports = Layer;